//
//  AFNHttpTools.m
//  DDViedo
//
//  Created by 赵 冰冰 on 15/3/11.
//  Copyright (c) 2015年 赵 冰冰. All rights reserved.
//

#import "AFNHttpTools.h"
#import "TimeTool.h"
#import "AFHTTPRequestOperationManager.h"
#import "NSString+encrypto.h"
#import "AESCipher.h"
#import "MD5Encryption.h"

#define SECU_KEY @"l6uQkhCS"

#define BaiduApiKey @"WSuEu0GCHQ2nScwXQdO6hKkX"
#define BaiduApiSecret @"hvIKWVY9YWchlTru9TS7KD8ChRQfWluW"


@implementation AFNHttpTools


+ (AFSecurityPolicy *)customSecurityPolicy
{
    //先导入证书，找到证书的路径
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"ssl_certificate" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    //AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    //allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    //如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = NO;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = YES;
    NSSet *set = [[NSSet alloc] initWithObjects:certData, nil];
    securityPolicy.pinnedCertificates = set;
    
    return securityPolicy;
}

+(void)requestWithUrl:(NSString *)url andPostDict:(NSDictionary *)postDict andAuthToken:(NSString*)andAuthToken successed:(RequestSuccessed)successed failed:(RequestFailed)failed{
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",nil];
    
    [manager.requestSerializer setValue:@"authorization" forHTTPHeaderField:@"authorization"];
    manager.requestSerializer.timeoutInterval = 5.0;
    if (IS_DISTRIBUTION) {
        [manager setSecurityPolicy:[self customSecurityPolicy]];
    }
    
    NSString * str = [url substringFromIndex:url.length - 1];
    if([str isEqualToString:@"/"])
    {
        url = [url substringToIndex:url.length - 1];
    }
    NSString * timeString = [TimeTool OSTime];
    NSMutableDictionary * paramDic = [NSMutableDictionary dictionaryWithDictionary:postDict];
    [paramDic setObject:timeString forKey:@"timestamp"];
    [paramDic setObject:[[NSString stringWithFormat:@"%@%@",timeString,SECU_KEY] sha1]forKey:@"signature"];
    
    [manager POST:url parameters:paramDic authToken:andAuthToken success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //DeBugLog(@"请求结果的Json串为:%@", [self jsonStringWithDict:responseObject]);
        successed(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //DeBugLog(@"请求错误原因是：%@", error);
        failed(error);
    }];
}

+ (void)getAppStoreInfoDataWithUrl:(NSString *)url
         andParameters:(id)parameters
             successed:(RequestSuccessed)successed
                failed:(RequestFailed)failed
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain",@"text/html",@"text/json",@"text/javascript",nil];
    if (IS_DISTRIBUTION) {
        [manager setSecurityPolicy:[self customSecurityPolicy]];
    }
    NSString * str = [url substringFromIndex:url.length - 1];
    if([str isEqualToString:@"/"])
    {
        url = [url substringToIndex:url.length - 1];
    }
    NSString * escapedUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    [manager GET:escapedUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //DeBugLog(@"JSON: %@", responseObject);
        successed(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //DeBugLog(@"Error: %@", error);
        failed(error);
    }];
    
}

+ (void)getDataNoTokenWithUrl:(NSString *)url
         andParameters:(id)parameters
             successed:(RequestSuccessed)successed
                failed:(RequestFailed)failed
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain",@"text/html",@"text/json",nil];
    
    if (IS_DISTRIBUTION) {
        [manager setSecurityPolicy:[self customSecurityPolicy]];
    }
    NSString * str = [url substringFromIndex:url.length - 1];
    if([str isEqualToString:@"/"])
    {
        url = [url substringToIndex:url.length - 1];
    }
    NSString * escapedUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSString * timeString = [TimeTool OSTime];
    NSMutableDictionary * paramDic = [NSMutableDictionary dictionaryWithDictionary:parameters];
    
    NSString * jsonString =[QHCommonTool dictionaryTOjsonString:paramDic];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\r\n"withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n"withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\t"withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@" "withString:@""];
    
    NSString * AESResult = AES128Encrypt(jsonString);
    
    
    NSString * key1 = [NSString stringWithFormat:@"%@%@",@"sWd3FmTa",[TimeTool nowTimeStr2]];
    NSString * result11 = [[MD5Encryption md5by32:key1] substringWithRange:NSMakeRange(0,8)];
    NSString *result1 = [result11 uppercaseStringWithLocale:[NSLocale currentLocale]];
    
    NSString * SHA1Result = [[NSString stringWithFormat:@"%@%@%@",AESResult,result1,timeString] sha1];
    [paramDic setObject:SHA1Result forKey:@"signature"];
    [paramDic setObject:timeString forKey:@"timestamp"];
    [paramDic setObject:@"IOS" forKey:@"appsource"];
    NSString * versionCode = kAppVersion;
    [paramDic setObject:versionCode forKey:@"nativeversion"];
    [manager GET:escapedUrl parameters:paramDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *aValue = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"A"]];
        if ([aValue isEqualToString:@"1"])
        {
            NSString *dStr = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"D"]];
           
            NSString *gzipStr = AES128Decrypt(dStr);
            
            NSData *data = [gzipStr base64Decoding];
            
            NSData *jsonData = [NSData gzipUncompress:data];
            
            NSError *toDicError;
            NSDictionary *responDic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&toDicError];
            if (toDicError)
            {
                DebugLog(@"%@",toDicError.domain);
                if (failed) {
                    failed(toDicError);
                }
            }
            else
            {
                if (successed) {
                    successed(responDic);
                }
            }
        }
        else
        {
            successed(responseObject);
        }
      
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DeBugLog(@"Error: %@", error);
        if (failed) {
            failed(error);
        }
    }];
    
}

+(void)getDataNoTokenAndSingature:(NSString *)url andParameters:(id)parameters  successed:(RequestSuccessed)successed failed:(RequestFailed)failed
{
    NSString *jsonString = [QHCommonTool returnJsonstringwithObject:parameters];
       
    NSString *tempStr = [[jsonString stringByUrlEncoding]uppercaseString];
    
    NSString *upperUnicode = [tempStr stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
        
    NSString * key2 = [NSString stringWithFormat:@"%@%@",@"G1eQdh@SD976RkYI",[TimeTool nowTimeStr2]];
       
    NSString * result22 = [[MD5Encryption md5by32:key2] substringWithRange:NSMakeRange(0,16)];
       
    NSString *result2 = [result22 uppercaseStringWithLocale:[NSLocale currentLocale]];
         
    NSString *aesStr =  [NSString AES128Encrypt:upperUnicode withKey:result2];//
         
    NSString *sha1key = [NSString stringWithFormat:@"%@%@",@"sWd3FmTa",[TimeTool nowTimeStr2]];
       
    NSString *sha1Str = [[MD5Encryption md5by32:sha1key] substringAtRange:NSMakeRange(0, 8)];  // 前8位
       
    NSString *sha1str2 = [sha1Str uppercaseStringWithLocale:[NSLocale currentLocale]];
       
    NSString *timeStamp = [TimeTool OSTime];
       
    NSString *sha1 = [[NSString stringWithFormat:@"%@%@%@",aesStr,sha1str2,timeStamp]sha1];
       
    NSString *signature = sha1;
       
    NSMutableDictionary *dict = [parameters mutableCopy]?:[NSMutableDictionary dictionary];
           
    [dict setValue:signature forKey:@"signature"];
    [dict setValue:timeStamp forKey:@"timestamp"];
    [dict setValue:@"IOS" forKey:@"appsource"];
    [dict setValue:kAppVersion forKey:@"appver"];
    [dict setValue:[QHCommonTool getDeviceID] forKey:@"clientid"];
    [dict setValue:kAppVersion forKey:@"nativeversion"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain",@"text/html",@"text/json",nil];
    if (IS_DISTRIBUTION) {
        [manager setSecurityPolicy:[self customSecurityPolicy]];
    }
    [manager GET2:nil url:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
       successed(responseObject);
   } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       failed(error);
   }];
}

+(void)requestWithFormAndSignature:(NSString *)url andPostDict:(NSDictionary *)postDict andAuthToken:(NSString *)andAuthToken successed:(RequestSuccessed)successed failed:(RequestFailed)failed{
        NSString *jsonString = [QHCommonTool returnJsonstringwithObject:postDict];
           
        NSString *tempStr = [[jsonString stringByUrlEncoding]uppercaseString];
        
        NSString *upperUnicode = [tempStr stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
        
        NSString * key2 = [NSString stringWithFormat:@"%@%@",@"G1eQdh@SD976RkYI",[TimeTool nowTimeStr2]];
           
        NSString * result22 = [[MD5Encryption md5by32:key2] substringWithRange:NSMakeRange(0,16)];
           
        NSString *result2 = [result22 uppercaseStringWithLocale:[NSLocale currentLocale]];
             
        NSString *aesStr =  [NSString AES128Encrypt:upperUnicode withKey:result2];//
             
        NSString *sha1key = [NSString stringWithFormat:@"%@%@",@"sWd3FmTa",[TimeTool nowTimeStr2]];
           
        NSString *sha1Str = [[MD5Encryption md5by32:sha1key] substringAtRange:NSMakeRange(0, 8)];  // 前8位
           
        NSString *sha1str2 = [sha1Str uppercaseStringWithLocale:[NSLocale currentLocale]];
           
        NSString *timeStamp = [TimeTool OSTime];
           
        NSString *sha1 = [[NSString stringWithFormat:@"%@%@%@",aesStr,sha1str2,timeStamp]sha1];
           
        NSString *signature = sha1;
           
        NSMutableDictionary *dict = [postDict mutableCopy];
               
        [dict setValue:signature forKey:@"signature"];
        [dict setValue:timeStamp forKey:@"timestamp"];
        [dict setValue:@"IOS" forKey:@"appsource"];
        [dict setValue:kAppVersion forKey:@"appver"];
        [dict setValue:[QHCommonTool getDeviceID] forKey:@"clientid"];
        [dict setValue:kAppVersion forKey:@"nativeversion"];
        
        AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [manager.requestSerializer setValue:@"authorization" forHTTPHeaderField:@"authorization"];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",nil];
         if (IS_DISTRIBUTION) {
             [manager setSecurityPolicy:[self customSecurityPolicy]];
         }
         [manager POST:url parameters:dict authToken:@"" success:^(AFHTTPRequestOperation *operation, id responseObject) {
             DeBugLog(@"%@",responseObject);
             NSString *aValue = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"A"]];
             if ([aValue isEqualToString:@"1"]) {
                 NSString *dValue = [NSString stringWithFormat:@"%@",responseObject[@"D"]];
                 NSString *gzipStr = AES128Decrypt(dValue);
                 NSData *data = [gzipStr base64Decoding];
                 NSData *jsonData = [NSData gzipUncompress:data];
                 NSError *toDicError = nil;
                 NSDictionary *responDic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&toDicError];
                 if (toDicError) {
                     if (failed) {
                         failed(toDicError);
                     }
                 }
                 else
                 {
                     if (successed) {
                         successed(responDic);
                     }
                 }
             }
             else
             {
                 if (successed) {
                     successed(responseObject);
                 }
             }
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             DeBugLog(@"%@",error);
             if (failed) {
                 failed(error);
             }
         }];
}

+(void)requestWithUrlAndSignatureNoToken:(NSString *)url andPostDic:(NSDictionary *)postDict successed:(RequestSuccessed)successed failed:(RequestFailed)failed{
    NSString *jsonString = [QHCommonTool returnJsonstringwithObject:postDict];
        
    NSString *tempStr = [[jsonString stringByUrlEncoding]uppercaseString];
    
    NSString *upperUnicode = [tempStr stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
    
    NSString * key2 = [NSString stringWithFormat:@"%@%@",@"G1eQdh@SD976RkYI",[TimeTool nowTimeStr2]];
       
    NSString * result22 = [[MD5Encryption md5by32:key2] substringWithRange:NSMakeRange(0,16)];
       
    NSString *result2 = [result22 uppercaseStringWithLocale:[NSLocale currentLocale]];
         
    NSString *aesStr =  [NSString AES128Encrypt:upperUnicode withKey:result2];//
         
    NSString *sha1key = [NSString stringWithFormat:@"%@%@",@"sWd3FmTa",[TimeTool nowTimeStr2]];
       
    NSString *sha1Str = [[MD5Encryption md5by32:sha1key] substringAtRange:NSMakeRange(0, 8)];  // 前8位
       
    NSString *sha1str2 = [sha1Str uppercaseStringWithLocale:[NSLocale currentLocale]];
       
    NSString *timeStamp = [TimeTool OSTime];
       
    NSString *sha1 = [[NSString stringWithFormat:@"%@%@%@",aesStr,sha1str2,timeStamp]sha1];
       
    NSString *signature = sha1;
       
    NSMutableDictionary *dict = [postDict mutableCopy];
           
    [dict setValue:signature forKey:@"signature"];
    [dict setValue:timeStamp forKey:@"timestamp"];
    [dict setValue:@"IOS" forKey:@"appsource"];
    [dict setValue:kAppVersion forKey:@"appver"];
    [dict setValue:[QHCommonTool getDeviceID] forKey:@"clientid"];
    [dict setValue:kAppVersion forKey:@"nativeversion"];
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
         
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",nil];
    
    [manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *aValue = [NSString stringWithFormat:@"%@",responseObject[@"A"]];
        if ([aValue isEqualToString:@"1"])
        {
            NSString *dValue = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"D"]];
            NSString *gzipStr = AES128Decrypt(dValue);
            NSData *data = [gzipStr base64Decoding];
            NSData *jsonData = [NSData gzipUncompress:data];
            NSError *toDicError = nil;
            NSDictionary *responDic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&toDicError];
            if (toDicError)
            {
                DeBugLog(@"%@",toDicError.domain);
                if (failed) {
                    failed(toDicError);
                }
            }
            else
            {
                if (successed) {
                    successed(responDic);
                }
            }
        }
        else
        {
            if (successed) {
                successed(responseObject);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failed) {
            failed(error);
        }
        DeBugLog(@"请求错误原因是：%@", error);
    }];
}

+(void)requestWithUrlAndSignature:(NSString *)url andPostDict:(NSDictionary *)postDict andAuthToken:(NSString*)andAuthToken successed:(RequestSuccessed)successed failed:(RequestFailed)failed{

    NSString *jsonString = [QHCommonTool returnJsonstringwithObject:postDict];
        
    NSString *tempStr = [[jsonString stringByUrlEncoding]uppercaseString];
    
    NSString *upperUnicode = [tempStr stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
    
    NSString * key2 = [NSString stringWithFormat:@"%@%@",@"G1eQdh@SD976RkYI",[TimeTool nowTimeStr2]];
       
    NSString * result22 = [[MD5Encryption md5by32:key2] substringWithRange:NSMakeRange(0,16)];
       
    NSString *result2 = [result22 uppercaseStringWithLocale:[NSLocale currentLocale]];
         
    NSString *aesStr =  [NSString AES128Encrypt:upperUnicode withKey:result2];//
         
    NSString *sha1key = [NSString stringWithFormat:@"%@%@",@"sWd3FmTa",[TimeTool nowTimeStr2]];
       
    NSString *sha1Str = [[MD5Encryption md5by32:sha1key] substringAtRange:NSMakeRange(0, 8)];  // 前8位
       
    NSString *sha1str2 = [sha1Str uppercaseStringWithLocale:[NSLocale currentLocale]];
       
    NSString *timeStamp = [TimeTool OSTime];
       
    NSString *sha1 = [[NSString stringWithFormat:@"%@%@%@",aesStr,sha1str2,timeStamp]sha1];
       
    NSString *signature = sha1;
       
    NSMutableDictionary *dict = [postDict mutableCopy];
           
    [dict setValue:signature forKey:@"signature"];
    [dict setValue:timeStamp forKey:@"timestamp"];
    [dict setValue:@"IOS" forKey:@"appsource"];
    [dict setValue:kAppVersion forKey:@"appver"];
    [dict setValue:[QHCommonTool getDeviceID] forKey:@"clientid"];
    [dict setValue:kAppVersion forKey:@"nativeversion"];
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
         
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",@"application/x-www-form-urlencoded",nil];
         
    [manager.requestSerializer setValue:@"authorization" forHTTPHeaderField:@"authorization"];

    if (IS_DISTRIBUTION) {
        [manager setSecurityPolicy:[self customSecurityPolicy]];
    }
    [manager POST:url parameters:dict authToken:@"" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *aValue = [NSString stringWithFormat:@"%@",responseObject[@"A"]];
        if ([aValue isEqualToString:@"1"])
        {
            NSString *dValue = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"D"]];
            NSString *gzipStr = AES128Decrypt(dValue);
            NSData *data = [gzipStr base64Decoding];
            NSData *jsonData = [NSData gzipUncompress:data];
            NSError *toDicError = nil;
            NSDictionary *responDic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&toDicError];
            if (toDicError)
            {
                DeBugLog(@"%@",toDicError.domain);
                if (failed) {
                    failed(toDicError);
                }
            }
            else
            {
                if (successed) {
                    successed(responDic);
                }
            }
        }
        else
        {
            if (successed) {
                successed(responseObject);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failed) {
            failed(error);
        }
        DeBugLog(@"请求错误原因是：%@", error);
    }];
}


+(void)asyncConvertAmrToText:(NSString *)localPath successed:(RequestSuccessed)successed failed:(RequestFailed)failed
{
    [self asyncGetBaiduApiAccess_tokenWith:BaiduApiKey andsecret:BaiduApiSecret successed:^(NSDictionary *dict) {
        if ([dict[@"error"]isEqualToString:@"invalid_client"])
        {
            DeBugLog(@"获取百度access_token失败：%@",dict);
        }
        else
        {
            NSString *url = @"https://vop.baidu.com/server_api";
            NSData *data = [NSData dataWithContentsOfFile:localPath];
            
            NSString *amrBase64 = [data base64EncodedStringWithOptions:0];
            
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:@"amr" forKey:@"format"];
            [param setValue:@(16000) forKey:@"rate"];
            [param setValue:@(1) forKey:@"channel"];
            [param setValue:@"" forKey:@"cuid"]; // 用户唯一标识
            NSString *access_token = [dict objectForKey:@"access_token"];
            [param setValue:access_token forKey:@"token"];
            [param setValue:amrBase64 forKey:@"speech"];   // 本地语音文件的二进制语音数据 ，需要进行base64 编码，与len参数连一起使用。
            int datalen = (int)data.length;
            [param setValue:@(datalen) forKey:@"len"]; //本地语音文件的的字节数，单位字节
            [param setValue:@(1537) forKey:@"dev_pid"];
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",@"application/x-www-form-urlencoded",nil];

            [manager POST:url parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
                if ([responseObject[@"rese"]isEqualToString:@"3300"])
                {
                    DeBugLog(@"获取百度access_token失败：%@",responseObject);
                }
                else
                {
                    if (successed) {
                        successed(responseObject);
                    }
                    DeBugLog(@"语音转文字失败：%@",responseObject);
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                DeBugLog(@"%@",error);
            }];
        }
    } failed:^(NSError *err) {
        DeBugLog(@"%@",err);
    }];
}

+(void)asyncGetBaiduApiAccess_tokenWith:(NSString *)client_id andsecret:(NSString *)client_secret successed:(RequestSuccessed)successed failed:(RequestFailed)failed
{
    NSString *url = @"https://aip.baidubce.com/oauth/2.0/token";
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@"client_credentials" forKey:@"grant_type"];
    [param setValue:client_id forKey:@"client_id"];
    [param setValue:client_secret forKey:@"client_secret"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",nil];
    [manager POST:url parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            if (successed) {
                successed(responseObject);
            }
            DeBugLog(@"%@",responseObject);
        }else{
            if (failed) {
                failed(nil);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failed) {
            failed(nil);
        }
        DebugLog(@"%@",error);
    }];
}

+(void)asyncGetHistoryMessageListWithUrlAndSignature:(NSString *)url andPostDict:(NSDictionary *)postDict andAuthToken:(NSString*)andAuthToken successed:(RequestSuccessed)successed failed:(RequestFailed)failed{
   
    NSString *jsonString = [QHCommonTool returnJsonstringwithObject:postDict];
        
    NSString *tempStr = [[jsonString stringByUrlEncoding]uppercaseString];

    NSString *upperUnicode = [tempStr stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
    
    NSString *key2 = [NSString stringWithFormat:@"%@%@",@"G1eQdh@SD976RkYI",[TimeTool nowTimeStr2]];
    
    NSString * result22 = [[MD5Encryption md5by32:key2] substringWithRange:NSMakeRange(0,16)];
          
    NSString *result2 = [result22 uppercaseStringWithLocale:[NSLocale currentLocale]];
            
    NSString *aesStr =  [NSString AES128Encrypt:upperUnicode withKey:result2];//
            
    NSString *sha1key = [NSString stringWithFormat:@"%@%@",@"sWd3FmTa",[TimeTool nowTimeStr2]];
          
    NSString *sha1Str = [[MD5Encryption md5by32:sha1key] substringAtRange:NSMakeRange(0, 8)];  // 前8位
          
    NSString *sha1str2 = [sha1Str uppercaseStringWithLocale:[NSLocale currentLocale]];
          
    NSString *timeStamp = [TimeTool OSTime];
          
    NSString *sha1 = [[NSString stringWithFormat:@"%@%@%@",aesStr,sha1str2,timeStamp]sha1];
          
    NSString *signature = sha1;
          
    NSMutableDictionary *dict = [postDict mutableCopy];
              
    [dict setValue:signature forKey:@"signature"];
    [dict setValue:timeStamp forKey:@"timestamp"];
    [dict setValue:@"IOS" forKey:@"appsource"];
    [dict setValue:kAppVersion forKey:@"appver"];
    [dict setValue:[QHCommonTool getDeviceID] forKey:@"clientid"];
    [dict setValue:kAppVersion forKey:@"nativeversion"];
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"authorization" forHTTPHeaderField:@"authorization"];

    if (IS_DISTRIBUTION) {
        [manager setSecurityPolicy:[self customSecurityPolicy]];
    }

    [manager POST:url parameters:dict authToken:@"" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([[responseObject objectForKey:@"A"]isEqualToString:@"1"])
        {
            NSString *dValue = [responseObject objectForKey:@"D"];
            NSString *gzipStr = AES128Decrypt(dValue);
            NSData *data = [gzipStr base64Decoding];
            NSData *jsonData = [NSData gzipUncompress:data];
            NSError *toDicError = nil;
            NSDictionary *responDic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&toDicError];
            if (toDicError) {
                DeBugLog(@"%@",toDicError.domain);
                if (failed) {
                    failed(toDicError);
                }
            }
            else
            {
                if (successed) {
                    successed(responDic);
                }
            }
        }
        else
        {
            if (successed) {
                successed(responseObject);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DeBugLog(@"%@",error);
        if (failed) {
            failed(error);
        }
    }];
}

+(void)requestVoiceFile:(NSString *)fileUrl to:(NSString *)localPath successBlock:(RequestSuccessed)successBlock errorBlock:(RequestFailed)errorBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fileUrl]];

    NSURLSessionDownloadTask *downTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

        
       } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
           
           NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
           NSString *fullPath = @"";
           // 不能用中文做文件存储路径。
           if ([response.suggestedFilename isContainChinese]) {
               NSString *nameStr = @"";
               if ([response.suggestedFilename containsString:@"."])
               { // 有格式，就用这个格式后缀。
                   NSArray *nameArr = [response.suggestedFilename componentsSeparatedByString:@"."];
                   nameStr = [NSString stringWithFormat:@"%@.%@",[TimeTool since1970Time],nameArr.lastObject];
               }
               else
               {// 没有格式就 只用时间戳 当文件名
                   nameStr = [NSString stringWithFormat:@"%@",[TimeTool since1970Time]];
               }
               fullPath = [filePath stringByAppendingPathComponent:nameStr];
           }
           else
           {
               fullPath = [filePath stringByAppendingPathComponent:response.suggestedFilename];
           }
           return [NSURL fileURLWithPath:fullPath];
           
       } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
           if (error) {
               if (errorBlock) {
                   errorBlock(error);
               }
           }else{
               NSError *error;
               NSFileManager *manager = [NSFileManager defaultManager];
               [manager removeItemAtPath:localPath error:&error];
               if ( [manager moveItemAtPath:filePath.path toPath:localPath error:&error])
               {
                   if (successBlock) {
                       successBlock(@{@"audioPath":localPath});
                   }
               }
               else
               {
                   if (errorBlock) {
                       errorBlock(error);
                   }
               }
           }
       }];
       [downTask resume];
}

+ (void)getDataWithUrl:(NSString *)url
         andParameters:(id)parameters
             successed:(RequestSuccessed)successed
                failed:(RequestFailed)failed
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain",@"text/html",@"text/json",nil];
    if (IS_DISTRIBUTION) {
        [manager setSecurityPolicy:[self customSecurityPolicy]];
    }
    NSString * str = [url substringFromIndex:url.length - 1];
    if([str isEqualToString:@"/"])
    {
        url = [url substringToIndex:url.length - 1];
    }
    NSString * escapedUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

//    NSString * timeString = [TimeTool OSTime];
    NSMutableDictionary * paramDic = [NSMutableDictionary dictionaryWithDictionary:parameters];
//    [paramDic setObject:timeString forKey:@"timestamp"];
//    [paramDic setObject:[[NSString stringWithFormat:@"%@%@",timeString,SECU_KEY] sha1]forKey:@"signature"];

    //DeBugLog(@"get请求url为 = %@",escapedUrl);
    [manager GET:escapedUrl parameters:paramDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //DeBugLog(@"JSON: %@", responseObject);
        successed(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //DeBugLog(@"Error: %@", error);
        failed(error);
    }];
}
+(void)downloadFile:(NSString *)fileUrl to:(NSString *)localPath successBlock:(RequestSuccessed)successBlock errorBlock:(RequestFailed)errorBlock
{
    NSURL *url = [NSURL URLWithString:fileUrl];
       NSURLRequest *request = [NSURLRequest requestWithURL:url];
       NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
       NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
       NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
           if (data) {
               NSError *error;
               NSFileManager *manager = [NSFileManager defaultManager];
               NSError *createDirErr = nil;
               if ([manager fileExistsAtPath:localPath]) {
                   [manager removeItemAtPath:localPath error:&error];
               }
               else
               {
                   if ([manager createDirectoryAtPath:localPath withIntermediateDirectories:YES attributes:nil error:&createDirErr]) {
                       DeBugLog(@"文件夹创建成功");
                   }else{
                       DeBugLog(@"文件夹创建失败%@",createDirErr);
                   }
               }
               if ([manager createFileAtPath:localPath contents:data attributes:nil])
               {
                   successBlock(@{@"filePath":localPath});
               }
               else
               {
                   errorBlock(error);
               }
           }else{
                errorBlock(error);
           }
       }];
       [task resume];
}

@end
